/*
 * 文 件 名 : HomeActivity.java
 * 版    权 : China Machi.Co.,Ltd.Copyright 2009-2011.All rights reserved
 * 描    述 : <描述>
 * 修 改 人 : lixg
 * 修改时间 : 2012-8-4
 * 跟踪单号 : <跟踪单号>
 * 修改单号 : <修改单号>
 * 修改内容 : <修改内容>
 */
package com.fire8.dolphin.ui;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.app.ListActivity;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.fire8.dolphin.model.Question;
import com.fire8.dolphin.ui.PullDownView.OnPullDownListener;
import com.fire8.dolphin.ui.diary.QuestionAddActivity;
import com.fire8.dolphin.ui.imgcache.AsynLoad;
import com.fire8.dolphin.utils.LogUtil;
import com.fire8.dolphin.web.RequestUtils;


/**
 * 主页面
 * 显示全部问题
 *
 * @author  lixg
 * @version [版本号,2012-8-4]
 * @see     [相关类/方法]
 * @since   [产品/模块]
 */
public class HomeActivity extends ListActivity implements OnItemClickListener
{
    //private static int index=1;
    private final String TAG="dolphin";
    //private QuestionDAO dao;
    private Button btnRight;
    private PullDownView pullDownView;
    private ScrollOverListView listView;
    private PopupWindow popButtonWin;
    //private ListView listView;
    private DolphinApplication app;
    private MyAdapter myAdapter;
    
    private AsynLoad asynLoad;
    private String orderby;
    //private List<HashMap<String, String>> list = new ArrayList<HashMap<String, String>>();
    private List<Question> list = new ArrayList<Question>();
    private Map<Integer,View> map;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.home);
        //dao = new QuestionDAO(this);
        app = (DolphinApplication)getApplication();
        orderby = app.getOrderBy();
        getElement();
        setElementEvent();
        //异步加载头像
        asynLoad = new AsynLoad();
        myAdapter = new MyAdapter(this);
        listView.setAdapter(myAdapter);
        findQuestionList();
        // list需要刷新时调用
        pullDownView.setOnPullDownListener(new OnPullDownListener() {
            
            @Override
            public void onRefresh() {
                new GetDataTask().execute(Question.QUERY_UP);
            }
            
            @Override
            public void onLoadMore() {
                new GetDataTask().execute(Question.QUERY_DOWN);
            }
        });
    }
    
    private void getElement()
    {
        btnRight = (Button)findViewById(R.id.title_bt_right);
        //listView = (ListView)findViewById(R.id.question_list);
        pullDownView = (PullDownView) findViewById(R.id.pulldownview);
        pullDownView.enableAutoFetchMore(true, 0);
        listView = pullDownView.getListView();
        listView.setDivider(this.getResources().getDrawable(R.color.list_bg));
        listView.setDividerHeight(10);
    }
    
    private void setElementEvent()
    {
        btnRight.setOnClickListener(new OnButtonListener());
        listView.setOnItemClickListener(this);
    }
    
    class OnButtonListener implements OnClickListener
    {

        @Override
        public void onClick(View v)
        {
            //弹出按钮窗口
            createPopupWindow(v);
//            Intent intent = new Intent(HomeActivity.this,QuestionAddActivity.class);
//            startActivity(intent);
            //finish();
        }
        
    }
    /**
     * 从本地库中查询问题列表
     * <功能详细描述> [参数说明]
     *
     * @author lixg
     * @see [类、类#方法、类#成员]
     */
    private void findQuestionList()
    {
        //DolphinApplication app = (DolphinApplication)getApplication();
//        Question question = new Question();
//        //question.setUserId(app.getUserId());
//        list = dao.findList(question,Question.QUERY_UP,app.PAGE_SIZE,orderby);
//        myAdapter.notifyDataSetChanged();
//        pullDownView.notifyDidDataLoad(false);
//        Log.i(TAG,"问题条数: "+list.size());
        new GetDataTask().execute(Question.QUERY_UP);
    }
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position,
            long id)
    {
        if(list.isEmpty())return;
        Log.d(TAG,"问题条数: "+list.size());
        Log.d(TAG,"position: "+position);
        if(position >= list.size())return;
        //HashMap<String, String> map= list.get(position);
//        Question question = list.get(position);
        //String locId = map.get(Question.C_Q_ID);
//        String remoteId = question.getRemoteId();
//        Log.i(TAG,"发送的问题ID: "+remoteId);
        Intent intent = new Intent(this,AnswerActivity.class);
        //intent.putExtra("locId", locId);
        //intent.putExtra("remoteId", remoteId);
        intent.putExtra("question", list.get(position));
        startActivity(intent);
    }
    
    public final class ViewHolder
    {
        
        public TextView tvContext;
        public TextView tvAnswerNum;
        public TextView tvDate;
        public TextView tvUserName;
        public ImageView imgHead;
    }
    public class MyAdapter extends BaseAdapter
    {
        private LayoutInflater mInflater; 
        
        public MyAdapter(Context context)
        {
            this.mInflater = LayoutInflater.from(context); 
            map = new HashMap<Integer, View>();
        }
        
        public int getCount()
        {
            return list.size();
        }

        
        public Object getItem(int position)
        {
            return list.get(position);
        }

        
        public long getItemId(int position)
        {
            return 0;
        }

        
        public View getView(int position, View convertView, ViewGroup parent)
        {
            View rowView = map.get(position);
            ViewHolder holder = null; 
            if (rowView == null)
            {
                holder = new ViewHolder();
                rowView = mInflater.inflate(R.layout.question_item, null);
                holder.tvContext = (TextView)rowView.findViewById(R.id.tv_context);
                holder.tvAnswerNum = (TextView)rowView.findViewById(R.id.tv_answer_num);
                holder.tvDate = (TextView)rowView.findViewById(R.id.tv_date);
                holder.tvUserName = (TextView)rowView.findViewById(R.id.tv_user_name);
                holder.imgHead = (ImageView)rowView.findViewById(R.id.img_head);
                //convertView.setTag(holder);
                rowView.setTag(holder);
                map.put(position, rowView);
            }
            else
            {
                holder = (ViewHolder)rowView.getTag();
            }
            
//            HashMap<String, String> map= list.get(position);
//            holder.tvContext.setText(map.get(Question.C_CONTEXT)); 
//            holder.tvAnswerNum.setText(map.get(Question.C_ANSWER_NUM));
//            holder.tvDate.setText(map.get(Question.C_UPDATE_DATE));
//            String userName = map.get(Question.C_USER_NAME);
//            holder.tvUserName.setText(userName==null?"未知":userName);
            LogUtil.d("position="+position);
            Question question = (Question)getItem(position);
            LogUtil.d("question is null ="+question==null?"yes":"no");
            holder.tvContext.setText(question.getContext()); 
            holder.tvAnswerNum.setText(question.getAnswerNum());
            holder.tvDate.setText(question.getUpdateDate());
            String userName = question.getUserName();
            holder.tvUserName.setText(userName==null?"未知":userName);
            //holder.imgHead.setTag(RequestUtils.getInstall().IMG_URL+question.getUserId()+".jpg");
            //holder.imgHead.setImageBitmap(BitmapFactory.decodeResource(getResources(),R.drawable.logo));
            asynLoad.showimgAnsy(holder.imgHead,RequestUtils.IMG_URL+question.getUserId()+".jpg");
            //anseylodar.showimgAnsy(holder.imgHead,RequestUtils.IMG_URL+question.getUserId()+".jpg");//异步加载图片
            return rowView;
        }
        
    }
    
    private class GetDataTask extends AsyncTask<Integer, Void, String> {

        @Override
        protected String doInBackground(Integer... params) {
            // 在这里可以做一些后台工作
            if(!RequestUtils.getInstall().isConnect(HomeActivity.this))
            {
                return "网络不可用";
            }
            int opt = params[0];
            //LogUtil.d("这是第"+index+"次取数据");
            //index++;
            if(Question.QUERY_UP == opt)
            {
                //向上刷新
                return refreshData();
            }else
            {
                //向下加载更多
                return loadMoreData();
            }
            
        }

        @Override
        protected void onPostExecute(String result) {
            // 下拉后增加的内容
            //mListItems.addFirst("Added after refresh...");
            
            LogUtil.d("list长度："+list.size());
            Toast.makeText(HomeActivity.this, result, Toast.LENGTH_LONG).show();
            
            myAdapter.notifyDataSetChanged();
            pullDownView.notifyDidRefresh(list.isEmpty());
            //getListView().setAdapter(new MyAdapter(HomeActivity.this));
            super.onPostExecute(result);
        }
    }
    
    //向上刷新数据
    private String refreshData()
    {
//        String remoteId = null;
//        if(list.size()>0)
//        {
//            //HashMap<String,String> map = list.get(0);
//            
//            remoteId = list.get(0).getQuesId();
//        }
//        if(StringUtil.isEmpty(remoteId))
//        {
//            remoteId = null;
//        }
        //LogUtil.d("请求远程数据时，remoteId:"+remoteId);
        //向上刷，按排序规则取最上面的数据，将原来的数据清空
        List<Question> questions = RequestUtils.getInstall().getQuestionList(0, Question.QUERY_UP, null,orderby);
        //将数据写入数据库
//        for (Question qus : questions)
//        {
//            dao.add(qus);
//        }
//        Question question = new Question();
//        question.setRemoteId(remoteId);
//        //LogUtil.d("查询本地数据时，remoteId:"+remoteId);
//        List<HashMap<String, String>> list3 = dao.findList(question,Question.QUERY_UP,app.PAGE_SIZE,orderby);
//        if(questions.size()>app.PAGE_SIZE)
//        {
//            list.clear();
//        }
        if(questions != null && !questions.isEmpty())
        {
            list.clear();
            map.clear();
            list.addAll(questions);
        }
        
        return "数据已更新";
    }
    
    //向下加载更多
    private String loadMoreData()
    {
        
        //取查询条件
        
        List<Question> questions = RequestUtils.getInstall().getQuestionList(list.size(), Question.QUERY_DOWN, null,orderby);
        if(!questions.isEmpty())
        {
            list.addAll(questions);
        }else
        {
            return "亲，你的数据是最新的了";
        }
        return "刷新完成";
    }
    
    private void createPopupWindow(View v){   
        if(popButtonWin == null)
        {
            LayoutInflater factory = LayoutInflater.from(this);  //加载popWindow的layout   
            final View buttonView = factory.inflate(R.layout.home_popup_button, null);   
            //Button btnAbout = (Button)buttonView.findViewById(R.id.btnAbout);
            popButtonWin = new PopupWindow(buttonView,170,270); //请注意，使用此构造方法，一定要指定popupWindow的长宽，之后调用popupWindow的showAXXX方法才会显示指定的contentView
            ColorDrawable cd = new ColorDrawable(-0000);
            popButtonWin.setBackgroundDrawable(cd);
            popButtonWin.setFocusable(true);
            popButtonWin.setTouchInterceptor(new OnTouchListener() {
                @Override
                public boolean onTouch(View v, MotionEvent event) {
                    if(event.getAction() == MotionEvent.ACTION_OUTSIDE)
                    {
                        Log.d("haoyuntu","按到外面了，关闭窗口");
                        popButtonWin.dismiss();
                        return true;
                    }
                    return false;
                }
            });
            popButtonWin.getContentView().findViewById(R.id.btn_new).setOnClickListener(new OnClickListener() {
                
                @Override
                public void onClick(View v) {
                    orderby="1";
                    list.clear();
                    new GetDataTask().execute(Question.QUERY_UP);
                    popButtonWin.dismiss();
                }
            });
            popButtonWin.getContentView().findViewById(R.id.btn_no_answer).setOnClickListener(new OnClickListener() {
                
                @Override
                public void onClick(View v) {
                    orderby="2";
                    list.clear();
                    new GetDataTask().execute(Question.QUERY_UP);
                    popButtonWin.dismiss();
                }
            });
            popButtonWin.getContentView().findViewById(R.id.btn_hot).setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    orderby="3";
                    list.clear();
                    new GetDataTask().execute(Question.QUERY_UP);
                    popButtonWin.dismiss();
                }
            });
            popButtonWin.getContentView().findViewById(R.id.btn_add_question).setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    //跳转到提问页面
                    Intent intent = new Intent(HomeActivity.this,QuestionAddActivity.class);
                    startActivity(intent);
                    popButtonWin.dismiss();
                }
            });
        }
        if(popButtonWin.isShowing())
        {
            popButtonWin.dismiss();
        }else
        {
            popButtonWin.showAsDropDown(v,10, 0);
        }
    } 
}
